package com.stylefeng.guns.modular.huamao.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.stylefeng.guns.core.util.MD5Util;
import com.stylefeng.guns.modular.huamao.common.GetOrderNum;
import com.stylefeng.guns.modular.huamao.dao.*;
import com.stylefeng.guns.modular.huamao.model.*;
import com.stylefeng.guns.modular.huamao.result.AppResult;
import com.stylefeng.guns.modular.huamao.service.*;
import com.stylefeng.guns.modular.huamao.service.impl.SktCartsServiceImpl;
import com.stylefeng.guns.modular.huamao.util.CacheUtil;
import com.stylefeng.guns.modular.huamao.util.RabbitSender;
import com.stylefeng.guns.modular.huamao.util.SessionUtils;
import com.stylefeng.guns.modular.huamao.util.StringUtils;
import com.stylefeng.guns.rest.common.constants.RabbitConstants;
import net.sf.ehcache.constructs.scheduledrefresh.OverseerJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
@CrossOrigin
@Controller
@RequestMapping(value = "/app")
public class AppCartsController {
    @Autowired
    ISktCartsService sktCartsService;
    @Autowired
    CacheUtil cacheUtil;
    @Autowired
    IUsersAddressService usersAddressService;
    @Autowired
    ISktShopFreightsService sktShopFreightsService;
    @Autowired
    IGoodsService goodsService;
    @Autowired
    IGoodsSpecsService  goodsSpecsService;
    @Autowired
    IGoodsCatsService goodsCatsService;
    @Autowired
    ISktShopsService sktShopsService;
    @Autowired
    ISpecCatsService specCatsService;
    @Autowired
    ISpecItemsService specItemsService;
    @Autowired
    SktOrderGoodsMapper sktOrderGoodsMapper;
    @Autowired
    SktOrdersMapper sktOrderMapper;
    @Autowired
    SktCartsMapper sktCartsMapper;
    @Autowired
    UsersAddressMapper usersAddressMapper;
    @Autowired
    ISktCartsService iSktCartsService;
    @Autowired
    SktShopsMapper sktShopsMapper;
    @Autowired
    SktShopFreightsMapper sktShopFreightsMapper;
    @Autowired
    ISktAreasService sktAreasService;
    @Autowired
    IMessagesService messagesService;
    @Autowired
    private IUsersService usersService;
    @Autowired
    private RabbitSender rabbitSender;
    /**
     * 新增购物车
     */
    @RequestMapping(value = "/Carts/addcarts")
    @ResponseBody
    public Object addcarts(@ModelAttribute("cartNum") Integer cartNum, @ModelAttribute("goodsId") Integer goodsId, @ModelAttribute("goodsSpecId") String goodsSpecId) {
        boolean flag=true;
        if(flag==false){
            return AppResult.ERROR("购买功能已关闭",-1);
        }

        //获取用户ID
        Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
        if(user == null){
            return AppResult.ERROR("对不起您还未登录",-2);
        }
        Integer userId = user.getUserId();
        Goods sktGoods1=new  Goods();
        sktGoods1.setGoodsId(goodsId);
        sktGoods1.setDataFlag(1);
        EntityWrapper<Goods> ewp = new EntityWrapper<Goods>(sktGoods1);
//        ewp.setEntity(new Goods());
//        ewp.where("dataFlag",1).and("goodsId",goodsId);
        Goods sktGoods = goodsService.selectOne(ewp);
        if (sktGoods==null){
            return  AppResult.ERROR("无效商品",-1);
        }
        if (sktGoods.getIsSale()==0){
            return  AppResult.ERROR("该商品已下架",-1);
        }
        if (sktGoods.getGoodsStatus()!=1){
            return  AppResult.ERROR("该商品为违规商品或者正在审核中",-1);
        }
        Integer shopId=sktGoods.getShopId();
        SktShops shops = sktShopsService.selectById(shopId);
        if (shops.getShopStatus()==0){
           return  AppResult.ERROR("该店铺已关闭",-1);
        }
        if (shops.getIsSelf()==0){
            boolean b=true;
            if(b==true){
                return  AppResult.ERROR("非自营店商品无法购买",-1);
            }
        }
        Integer shopUserId = shops.getUserId();
        if(userId.equals(shopUserId)){
            return  AppResult.ERROR("不可以购买自己店铺的商品",-1);
        }

        /**
         * 从数据库中取出库存，放到缓存中。
         * 先判断缓存中有没有对应的库存
         */
        // 库存ID
//        Integer goodsId  = sktCarts.getGoodsId();
        String redisKey = "redis_key:stock:" + goodsId;
        if(!cacheUtil.isKeyInCache(redisKey)){
            /**
             * 缓存的数据格式
             *redisKey:{
             *     "goodsStock":goodsStock,
             *     "isSpec":true/false,
             *     "spec": {
             *         specId:specStock,
             *     }
             *}
             */
            JSONObject map = new JSONObject();

            Goods goods2 = new Goods();
            goods2 = goodsService.selectById(goodsId);
            map.put("goodsStock",goods2.getGoodsStock());
            if(goodsSpecId.equals("0") || goodsSpecId == "" || goodsSpecId == null){
                map.put("isSpec",false);
            }else{
                map.put("isSpec",true);
                JSONObject specsMap = new JSONObject();
                GoodsSpecs goodsSpecs1 =  new GoodsSpecs();
                goodsSpecs1.setGoodsId(goodsId);
                EntityWrapper<GoodsSpecs> entityWrapper =  new EntityWrapper<GoodsSpecs>(goodsSpecs1);
                List<GoodsSpecs> goodsSpecsList  = goodsSpecsService.selectList(entityWrapper);
                for(GoodsSpecs temp:goodsSpecsList){
                    specsMap.put(temp.getId().toString(),temp.getSpecStock());
                }
                map.put("spec",specsMap);
            }

            cacheUtil.set(redisKey,map, Long.valueOf(60*30));
        };

        SktCarts sktCarts = new SktCarts();
        //sktCarts.setCartNum(cartNum);
        sktCarts.setGoodsId(goodsId);
        sktCarts.setIsCheck(1);
        sktCarts.setGoodsSpecId(goodsSpecId);
        sktCarts.setUserId(user.getUserId());
        //sktCarts.setUserId(6237);

        try {
            EntityWrapper<SktCarts> ew = new EntityWrapper<SktCarts>(sktCarts);
            /**
             * 查询是否有同型号的商品
             */
            SktCarts sc = sktCartsService.selectOne(ew);
            /**
             * 如果没有同型号的商品，就增加一条商品信息
             * 如果有同型号的商品，就在改变商品的数量
             */
            if(sc == null){
                SktCarts isktCarts = new SktCarts();
                isktCarts.setCartNum(cartNum);
                isktCarts.setGoodsId(sktCarts.getGoodsId());
                isktCarts.setIsCheck(1);
                isktCarts.setGoodsSpecId(sktCarts.getGoodsSpecId());
                isktCarts.setUserId(user.getUserId());
                sktCartsService.insert(isktCarts);
            }else{
                int temp = sc.getCartNum() + cartNum;
                sc.setCartNum(temp);
                EntityWrapper<SktCarts> entityWrapper = new EntityWrapper<SktCarts>(sc);
                sktCartsService.updateById(sc);
            }
            return  AppResult.OK("添加成功");
        } catch (Exception e) {
            return  AppResult.ERROR("添加失败");
        }

    }

    /**
     * 删除购物车
     */
    @RequestMapping(value = "/Carts/delCarts")
    @ResponseBody
    public Object delCarts(@ModelAttribute("cartId") String cartId) {
        String[] strs=cartId.split(",");
        try {
            for(int i=0;i<strs.length;i++){
                sktCartsService.deleteById(Integer.parseInt(strs[i]));
            }
            return AppResult.OK("删除成功");
        }catch (Exception e){
            return  AppResult.ERROR("删除失败");
        }
    }
    /**
     * 点击立即购买获取参数
     */
    @RequestMapping(value = "/Carts/BuyImmediately")
    @ResponseBody
    public AppResult BuyImmediately(@ModelAttribute("cartNum") String cartNum,@ModelAttribute("goodsId") Integer goodsId,
                                 @ModelAttribute("goodsSpecId") String goodsSpecId,@ModelAttribute("specIds") String specIds){
        boolean flag=true;
        if (flag==false){
            return AppResult.ERROR("购买功能已关闭",-1);
        }

        //返回的数据
        Map<String,Object> data = new HashMap<String,Object>();

        //获取用户ID
        Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
        if(user == null){
            return AppResult.ERROR("对不起您还未登录",-2);
        }
        //Integer userId = 124;
        Integer userId = user.getUserId();
        Goods sktGoods1=new  Goods();
        sktGoods1.setGoodsId(goodsId);
        sktGoods1.setDataFlag(1);
        EntityWrapper<Goods> ewp = new EntityWrapper<Goods>(sktGoods1);
//        ewp.setEntity(new Goods());
//        ewp.where("dataFlag",1).and("goodsId",goodsId);
        Goods sktGoods = goodsService.selectOne(ewp);
        if (sktGoods==null){
            return  AppResult.ERROR("无效商品",-1);
        }
        if (sktGoods.getIsSale()==0){
            return  AppResult.ERROR("该商品已下架",-1);
        }
        if (sktGoods.getGoodsStatus()!=1){
            return  AppResult.ERROR("该商品为违规商品或者正在审核中",-1);
        }
        Integer shopId=sktGoods.getShopId();
        SktShops shops = sktShopsService.selectById(shopId);
        if (shops.getIsSelf()==0){
            boolean b=true;
            if(b==false){
                return  AppResult.ERROR("非自营店商品无法购买",-1);
            }
        }
        Integer shopUserId = shops.getUserId();
        if(userId.equals(shopUserId)){
            return  AppResult.ERROR("不可以购买自己店铺的商品",-1);
        }
        UsersAddress usersAddress = new UsersAddress();
        usersAddress.setUserId(user.getUserId());
        usersAddress.setIsDefault(1);
        EntityWrapper<UsersAddress> ew = new EntityWrapper<UsersAddress>(usersAddress);
        /**
         * 获取地址信息详情
         */
        UsersAddress resultAdd = new UsersAddress();
        resultAdd = usersAddressService.selectOne(ew);
        if(resultAdd == null){
            //return AppResult.ERROR("请设置默认地址");
            Map<String,Object> address = new HashMap<String,Object>();
            data.put("address",address);
        }else{
            //设置返回地址的值
            Map<String,Object> address = new HashMap<String,Object>();
            address.put("userName",resultAdd.getUserName());
            address.put("userPhone",resultAdd.getUserPhone());
            address.put("provinceId",resultAdd.getProvinceId());
            address.put("cityId",resultAdd.getCityId());
            address.put("areaId",resultAdd.getAreaId());
            address.put("userAddress",resultAdd.getUserAddress());
            address.put("isDefault",resultAdd.getIsDefault());
            address.put("addressId",resultAdd.getAddressId());
            address.put("areaId2",resultAdd.getCityId());
            SktAreas sktAreasProvince = sktAreasService.selectById(resultAdd.getProvinceId());
            String provinceName=sktAreasProvince.getAreaName();
            SktAreas sktAreasCity = sktAreasService.selectById(resultAdd.getCityId());
            String cityName = sktAreasCity.getAreaName();
            SktAreas sktAreasArea = sktAreasService.selectById(resultAdd.getAreaId());
            String areaName = sktAreasArea.getAreaName();
            String name=provinceName+cityName+areaName;
            address.put("name",name);
            //添加返回的地址信息
            data.put("address",address);
        }


        /**
         * 通过物品id获取物品详情
         */
        Goods goods = new Goods();
        goods = goodsService.selectById(goodsId);

        //查询总运费
        SktShopFreights sktShopFreights = new SktShopFreights();
        sktShopFreights.setShopId(goods.getShopId());
        if(resultAdd != null){
            sktShopFreights.setAreaId2(resultAdd.getCityId());
        }

        EntityWrapper<SktShopFreights> ssfew = new EntityWrapper<SktShopFreights>(sktShopFreights);
        //接收运费对象
        SktShopFreights resultssf = new SktShopFreights();
        resultssf = sktShopFreightsService.selectOne(ssfew);
        //如果为空，说明商家在此地区没有填运费，默认设置为0
        if(resultssf == null){
            //添加返回的运费
            data.put("allAddressPrice",0);
        }else {
            //添加返回的运费
            data.put("allAddressPrice", resultssf.getFreight());
        }

        /**
         * 获取商品规格数据
         */
        GoodsSpecs goodsSpecs = new GoodsSpecs();
        goodsSpecs.setGoodsId(goodsId);
        goodsSpecs.setSpecIds(specIds);
        EntityWrapper<GoodsSpecs> gsew = new EntityWrapper<GoodsSpecs>(goodsSpecs);

        GoodsSpecs resultgs = new GoodsSpecs();

        if (gsew!=null){
            resultgs = goodsSpecsService.selectOne(gsew);
        }
       /**
         * 获取商品分类详细信息
         */
       GoodsCats goodsCats = new GoodsCats();
       goodsCats = goodsCatsService.selectById(goods.getGoodsCatId());

       /**
        * 获取商品规格
        */
       String SpecName = "";
        String[] StrArray = specIds.split(":");
        for (int i = 0; i < StrArray.length; i++) {
           SpecItems specItems = new SpecItems();
            SpecCats specCats = new SpecCats();
           specItems = specItemsService.selectById(Integer.parseInt(StrArray[i]));
           if(specItems!=null){
               specCats =  specCatsService.selectById(specItems.getCatId());
                System.out.println(i);
                System.out.println(specCats.getCatName());
               System.out.println(specItems.getItemName());
                SpecName += specCats.getCatName() +":"+specItems.getItemName()+"@@_@@";
           }


        }

       /**
         * 获取商店详细信息
         */
       SktShops sktShops = new SktShops();
        sktShops = sktShopsService.selectById(goods.getShopId());
        Map<String,Object> goodsDetails = new HashMap<String, Object>();
        if (resultgs!=null){
           goodsDetails.put("specPrice",resultgs.getSpecPrice());
            goodsDetails.put("specStock",resultgs.getSpecStock());
            goodsDetails.put("specIds",resultgs.getSpecIds());
        }else{
           goodsDetails.put("specPrice",goods.getShopPrice());
            goodsDetails.put("specStock","0");
            goodsDetails.put("specIds","0");
       }
       goodsDetails.put("catName",goodsCats.getCatName());
        goodsDetails.put("userId",user.getUserId());
        goodsDetails.put("shopId",goods.getShopId());
       goodsDetails.put("shopName",sktShops.getShopName());
        goodsDetails.put("goodsId",goods.getGoodsId());
       goodsDetails.put("goodsName",goods.getGoodsName());
       goodsDetails.put("shopPrice",goods.getShopPrice());
        goodsDetails.put("goodsStock",goods.getGoodsStock());
       goodsDetails.put("isSpec",goods.getIsSpec());

       goodsDetails.put("goodsImg",goods.getGoodsImg());
        goodsDetails.put("payShopping",goods.getPayShopping());
       //商品购物券数量
        goodsDetails.put("payShopping",goods.getPayShopping());

        goodsDetails.put("goodsCatId",goods.getGoodsCatId());
       goodsDetails.put("SpecName",SpecName);

        List<Object> list = new ArrayList<Object>();

        list.add(goodsDetails);

        Map<String,Object> goodsMap = new HashMap<String,Object>();
        goodsMap.put("catName",sktShops.getShopName());
       goodsMap.put("list",list);

       List<Object> goodsList = new ArrayList<Object>();
        goodsList.add(goodsMap);

        //添加返回的商品信息
       data.put("goodsList",goodsList);

       //添加返回的购买数量
       data.put("cartNum",cartNum);

       //添加返回的商品规格ID
       data.put("goodsSpecId",goodsSpecId);

        //添加返回的总价格
       BigDecimal BcartNum = BigDecimal.valueOf(Integer.parseInt(cartNum));
       if(resultgs!=null){
            if(resultssf == null){
                data.put("allPrice", resultgs.getSpecPrice().multiply(BcartNum));
           }else {
                data.put("allPrice", resultgs.getSpecPrice().multiply(BcartNum));
            }

       }else {
            if(resultssf == null){
                data.put("allPrice", goods.getShopPrice().multiply(BcartNum));
            }else {
               data.put("allPrice", goods.getShopPrice().multiply(BcartNum));
           }

       }


      //添加返回的总积分
        Integer allPayScore = goods.getPayScore()*Integer.parseInt(cartNum);
       data.put("allPayScore",allPayScore);
        //添加返回的总华宝
       BigDecimal allPayKaiyuan=goods.getPayKaiyuan().multiply(new BigDecimal(cartNum));
       data.put("allPayKaiyuan",allPayKaiyuan);
       BigDecimal allPayShopping=goods.getPayShopping().multiply(new BigDecimal(cartNum));
       data.put("allPayShopping",allPayShopping);


      return AppResult.OK("",data);
   }

    /**
     *立即购买提交订单
     */
    @RequestMapping(value = "/orders/orderPayBuy")
    @ResponseBody
    public Object orderPayBuy(@ModelAttribute("cartNum") Integer cartNum,
                              @ModelAttribute("goodsId") Integer goodsId,
                              @ModelAttribute("goodsSpecId") String goodsSpecId,
                              @ModelAttribute("specIds") String specIds,
                              @ModelAttribute("addressId") String addressId,
                              @ModelAttribute("isInvoice") Integer isInvoice,
                              @ModelAttribute("invoiceClient") String invoiceClient,
                              @ModelAttribute("orderRemarks") String orderRemarks,
                              @ModelAttribute("allAddressPrice") BigDecimal allAddressPrice,
                              @ModelAttribute("allPrice") BigDecimal allPrice,
                              @ModelAttribute("allPayScore") Integer allPayScore,

                              @ModelAttribute("shopPrice") BigDecimal shopPrice,
                              @ModelAttribute("shopId") Integer shopId,
                              @ModelAttribute("goodsName") String goodsName,
                              @ModelAttribute("goodsImg") String goodsImg
    ){
      try {
          boolean b=true;
          if (b==false){
            return AppResult.ERROR("对不起暂不支持购买",-1);
          }
        //返回的数据
        Map<String,Object> map = new HashMap<String,Object>();
        //获取用户ID
        Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
        if(user == null){
            return AppResult.ERROR("对不起您还未登录",-2);
        }
        //Integer userId = 124;
        Integer userId = user.getUserId();

          /**
           * 从数据库中取出库存，放到缓存中。
           * 先判断缓存中有没有对应的库存
           */
          // 库存ID
//          Integer goodsId  = sktCarts.getGoodsId();
          String redisKey = "redis_key:stock:" + goodsId;
          if(!cacheUtil.isKeyInCache(redisKey)) {
              /**
               * 缓存的数据格式
               *redisKey:{
               *     "goodsStock":goodsStock,
               *     "isSpec":true/false,
               *     "spec": {
               *         specId:specStock,
               *     }
               *}
               */
              JSONObject map1 = new JSONObject();

              Goods goods1 = new Goods();
              goods1 = goodsService.selectById(goodsId);
              map1.put("goodsStock", goods1.getGoodsStock());
              if (specIds == "" || specIds == null || specIds.equals("0")) {
                  map1.put("isSpec", false);
              } else {
                  map1.put("isSpec", true);
                  JSONObject specsMap = new JSONObject();
                  GoodsSpecs goodsSpecs1 = new GoodsSpecs();
                  goodsSpecs1.setGoodsId(goodsId);
                  EntityWrapper<GoodsSpecs> entityWrapper = new EntityWrapper<GoodsSpecs>(goodsSpecs1);
                  List<GoodsSpecs> goodsSpecsList = goodsSpecsService.selectList(entityWrapper);
                  for (GoodsSpecs temp : goodsSpecsList) {
                      specsMap.put(temp.getId().toString(), temp.getSpecStock());
                  }
                  map1.put("spec", specsMap);
              }

              cacheUtil.set(redisKey, map1, Long.valueOf(60 * 30));
          };

          /**
           * 从缓存中获取库存
           */
//          String redisKey = "redis_key:stock:" + goodsId;
          Integer Stock = 0;
          JSONObject jsonObject = JSONObject.parseObject(cacheUtil.simpleGet(redisKey).toString());
          if(jsonObject.getBoolean("isSpec")){
              JSONObject spec = jsonObject.getJSONObject("spec");
              Stock = spec.getInteger(goodsSpecId);
          }else{
              Stock = jsonObject.getInteger("goodsStock");
          };
            if(Stock < cartNum){
                SktShops sktShops = sktShopsMapper.selectById(shopId);
                List<Integer> listt = new ArrayList<Integer>();
                listt.add(sktShops.getUserId());
                messagesService.addMessages(1,1,listt,"您的商品"+goodsName+"库存数量不足,请尽快补货",null);

                return AppResult.ERROR("商品库存不足");
            }
        //查询商品信息
        Goods goods = goodsService.selectById(goodsId);

        //查询用户地址信息
        UsersAddress usersAddress = usersAddressService.selectById(addressId);
        if(usersAddress == null){
            return AppResult.ERROR("地址不存在");
        }
        //订单状态

        SktOrderGoods sog = new SktOrderGoods();
        SktOrders so = new SktOrders();

        sog.setGoodsNum(cartNum);
        sog.setGoodsName(goodsName);
        sog.setGoodsImg(goodsImg);
        sog.setGoodsId(goodsId);
        sog.setGoodsSpecId(goodsSpecId);
        so.setAreaId(usersAddress.getAreaId());
        so.setAreaIdPath(usersAddress.getProvinceId()+"_"+usersAddress.getCityId()+"_"+usersAddress.getAreaId());
        so.setUserName(usersAddress.getUserName());
        so.setUserAddress(usersAddress.getUserAddress());
        so.setUserPhone(usersAddress.getUserPhone());
        so.setIsInvoice(isInvoice);
        so.setInvoiceClient(invoiceClient);
        so.setOrderRemarks(orderRemarks);
        so.setDeliverMoney(allAddressPrice);
        so.setTotalMoney(allPrice.add(allAddressPrice));
        so.setPayScore(allPayScore);
        BigDecimal  allPayKaiyuan=new BigDecimal(100);
        BigDecimal  allPayShopping=goods.getPayShopping().multiply(new BigDecimal(cartNum));
        so.setTotalShopping(allPayShopping);
        so.setKaiyuan(allPayKaiyuan);
        sog.setPayScore(allPayScore);
        sog.setGoodsPrice(shopPrice.multiply(new BigDecimal(cartNum)));
        so.setShopId(shopId);
        so.setOrderStatus(-2);
        so.setCreateTime(new Date());
        so.setUserId(userId);
        so.setIsPay(0);
        so.setIsClosed(0);
        so.setGoodsMoney(shopPrice.multiply(new BigDecimal(cartNum)));
        so.setPayType(4);
        so.setRealMoney(new BigDecimal(0));
        so.setCash(new BigDecimal(0));
        so.setKaiyuan(new BigDecimal(0));
        so.setKaiyuanFee(new BigDecimal(0));
        so.setIsRefund(0);
        so.setIsAppraise(0);
        so.setCancelReason(0);
        so.setDataFlag(1);

        sog.setScoreRatio(goods.getScoreRatio());
        sog.setScore(so.getGoodsMoney().multiply(new BigDecimal(sog.getScoreRatio())));
        sog.setGoodsSpecNames(null);

        // 生成订单号
        SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String strDate = sfDate.format(new Date());
        String num = GetOrderNum.getRandom620(2);
        so.setOrderNo("2" + strDate + num);
        String orderNo1 = "2" + strDate + num;
        rabbitSender.sendMessage(RabbitConstants.MQ_EXCHANGE_ORDER,RabbitConstants.MQ_ROUTING_KEY_ORDER,orderNo1);
        String redisKey1 = "redis_key:orderNo:" + orderNo1;
        cacheUtil.set(redisKey1,orderNo1,Long.valueOf(60*30));
        // 生成流水号
        String orderunique =StringUtils.getOrderIdByTime("2");
        so.setOrderunique(orderunique);
        sktOrderMapper.insert(so);
        sog.setOrderId(so.getOrderId());
        sktOrderGoodsMapper.insert(sog);
        String orderNo = so.getOrderNo();

          /**
           *减少缓存的中的库存
           */
//          String redisKey = "redis_key:stock:" + goodsId;
          JSONObject jsonObject2 = JSONObject.parseObject(cacheUtil.simpleGet(redisKey).toString());
          if(jsonObject2.getBoolean("isSpec")){
              jsonObject2.put("goodsStock",jsonObject2.getInteger("goodsStock")-cartNum);
              JSONObject  specObj = jsonObject2.getJSONObject("spec");
              specObj.put(goodsSpecId,specObj.getInteger(goodsSpecId)-cartNum);
          }else{
              jsonObject2.put("goodsStock",jsonObject2.getInteger("goodsStock")-cartNum);
          }
          cacheUtil.set(redisKey,jsonObject2,Long.valueOf(60*30));

          SktShops sktShops = sktShopsMapper.selectById(shopId);
          List<Integer> listt = new ArrayList<Integer>();
          listt.add(sktShops.getUserId());
          messagesService.addMessages(1,1,listt,"您有一笔新的订单【"+orderNo+"】待处理.",null);


          //System.out.println(orderNo);
        	 return  AppResult.OK("提交订单成功",orderNo);
		} catch (Exception e) {
			return AppResult.ERROR("提交错误");
		}

    }

    /**
     * 购物车
     * @param pageIndex
     * @return
     */
    @RequestMapping(value = "Carts/carts")
    @ResponseBody
    public AppResult carts(@ModelAttribute("pageIndex")Integer pageIndex){
        PageHelper.startPage(pageIndex,20);
        //获取用户ID
        Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
        if(user == null){
            return AppResult.ERROR("对不起您还未登录",-2);
        }
     //   Integer userId = 6247;
        Integer userId = user.getUserId();
        Map<String,Object> maps = sktCartsService.appCarts(userId);
        Integer code = (Integer)maps.get("code");
        if(code == 0){
            String msg = (String)maps.get("msg");
            return AppResult.ERROR(msg);
        }
        List<Map<String,Object>> list = (List<Map<String,Object>>)maps.get("data");
        JSONObject json=new JSONObject();
        if (list==null && list.size()>0){
            PageInfo pageInfo=new PageInfo(list);
            json.put("tatolPage",pageInfo.getPages());
        }else {
            json.put("tatolPage",1);
        }


        json.put("maps",list);
        return AppResult.OK("获取成功！",json);
    }
    /*
     * 提交订单（不能用）
     * */
    @RequestMapping(value = "/orders/orderPayBu")
    @ResponseBody
    public AppResult orderPa(@ModelAttribute("userId") Integer userId,
					          @ModelAttribute("addressId") Integer addressId,
					          @ModelAttribute("isInvoice") Integer isInvoice,
					          @ModelAttribute("invoiceClient") Integer invoiceClient,
					          @ModelAttribute("orderRemarks") String orderRemarks,
					          @ModelAttribute("cartId") Integer cartId){
    	 //返回的数据
        Map<String,Object> map = new HashMap<String,Object>();
    	//根据cartId查询购物车
    	SktCarts carts = sktCartsMapper.selectById(cartId);
    	//获取数据
    	carts.getCartId();
    	carts.getCartNum();
    	carts.getGoodsId();
    	carts.getGoodsSpecId();
    	carts.getIsCheck();
    	carts.getIsDirect();
    	carts.getUserId();
    	//根据addressId查询用户所在地址
    	UsersAddress ua = usersAddressMapper.selectById(addressId);
    	ua.getProvinceId();
    	ua.getCityId();
    	ua.getAreaId();

    	 map.put("carts", carts);
    	 SktOrderGoods sog = new SktOrderGoods();
         SktOrders so = new SktOrders();

         so.setAreaId(addressId);
         so.setIsInvoice(isInvoice);
         so.setOrderRemarks(orderRemarks);
         so.setCreateTime(new Date());
         so.setUserId(userId);


         // 生成订单号
         SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
         String strDate = sfDate.format(new Date());
         String num = GetOrderNum.getRandom620(2);
         so.setOrderNo("2" + strDate + num);
         String orderNo1 = "2" + strDate + num;
         rabbitSender.sendMessage(RabbitConstants.MQ_EXCHANGE_ORDER,RabbitConstants.MQ_ROUTING_KEY_ORDER,orderNo1);
         String redisKey1 = "redis_key:orderNo:" + orderNo1;
         cacheUtil.set(redisKey1,orderNo1,Long.valueOf(60*30));
         sktOrderMapper.insert(so);
         sog.setOrderId(so.getOrderId());
         sktOrderGoodsMapper.insert(sog);
         String orderNo = so.getOrderNo();
         //System.out.println(orderNo);
         try {
         	 return  AppResult.OK("提交订单成功",orderNo);
 		} catch (Exception e) {
 			return AppResult.ERROR("提交错误");
 		}
     }
    //校验密码
    @RequestMapping(value="/user/checkPwd")
    @ResponseBody
    public JSONObject checkPwd(@ModelAttribute("password") String password,
	          				  @ModelAttribute("field") String field){
    	JSONObject json = new JSONObject();
        //获取用户ID
        Users user2 =(Users) cacheUtil.get(SessionUtils.getSessionId());
        if(user2 == null){
        	json.put("status",-2);
        	json.put("msg","对不起您还未登录");
            return json;
        }
        //Integer userId = 124;
        Integer userId = user2.getUserId();
        Users user = usersService.selectById(userId);
        //获取登录密码
        String loginPwd = user.getLoginPwd();
        //获取支付密码
        String payPwd = user.getPayPwd();

		password = MD5Util.encrypt(password+user.getLoginSecret());
//		String lPwd = MD5Util.encrypt(loginPwd+user.getLoginSecret());


		if("payPwd".equals(field)){
			if (user.getPayPwd()==null){
				json.put("status","-1");
				json.put("msg","请设置支付密码");
				return  json;
			}
			if ("".equals(password) ||password==null){
				json.put("status","-1");
				json.put("msg","请输入支付密码");
				return  json;
			}
			if (password.equals(user.getPayPwd())){
					json.put("status","1");
                    json.put("msg","支付成功");
				//	json.put("msg","下单成功");
			}else {
				json.put("status","-1");
				json.put("msg","支付密码错误，请重新输入");
			}
			return  json;
		}else{
			if ("".equals(password) ||password==null){
				json.put("status","-1");
				json.put("msg","请输入登录密码");
				return  json;
			}
			if (password.equals(user.getLoginPwd())){
					json.put("status","1");
					json.put("msg","登录成功");
				//	json.put("msg","下单成功");
			}else{
				json.put("status","-1");
				json.put("msg","登录账户或密码错误，请重新输入");
			}
			return  json;
		}
		}
    /**
     * 购选中或取消购物车商品Carts-cartsCheck
     */
    @RequestMapping(value = "/Carts/cartsCheck")
    @ResponseBody
    public AppResult cartsCheck(@ModelAttribute("isCheck")Integer isCheck,
    		@ModelAttribute("cartId")Integer cartId,
    		@ModelAttribute("userId")Integer userId,
            @ModelAttribute("goodsId")Integer goodsId){
        if (isCheck==1){
            Goods sktgoods= goodsService.selectById(goodsId);
            if (sktgoods.getIsSale()==0 ){
                return  AppResult.ERROR("该商品已下架");
            }
            if (sktgoods.getGoodsStatus()!=1){
                return  AppResult.ERROR("该商品违规或正在审核中");
            }
            if (sktgoods.getDataFlag()==-1){
                return  AppResult.ERROR("该商品已失效");
            }
            Integer shopId=sktgoods.getShopId();
            SktShops shops = sktShopsService.selectById(shopId);
            Integer shopUserId = shops.getUserId();
            if(userId.equals(shopUserId)){
                return  AppResult.ERROR("不可以购买自己店铺的商品");
            }
            if (shops.getShopStatus()==0){
                return  AppResult.ERROR("该商品所属商家已关闭");
            }
            if (shops.getDataFlag()==-1){
                return  AppResult.ERROR("该商家已失效");
            }
        }
    	SktCarts sktCarts = new SktCarts();
    	sktCarts.setIsCheck(isCheck);
    	EntityWrapper<SktCarts> ew = new EntityWrapper<SktCarts>();
    	ew.where("cartId={0}", cartId).and("userId={0}",userId);
        boolean update = iSktCartsService.update(sktCarts, ew);
        return update==true?AppResult.OK("修改成功"):AppResult.ERROR("修改失败");
    }

    /**
     * 购物车 结算
     * @param addressId
     * @param isInvoice  是否需要发票
     * @param invoiceClient  发票抬头
     * @param orderRemarks
     * @return
     */
    @RequestMapping(value = "/Orders/orderPay")
    @ResponseBody
    public AppResult appOrderPay(@ModelAttribute("addressId")Integer addressId,
                                 @ModelAttribute("isInvoice")Integer isInvoice,
                                 @ModelAttribute("invoiceClient") String invoiceClient,
                                 @ModelAttribute("orderRemarks") String orderRemarks){
        //获取用户ID
        Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
        if(user == null){
            return AppResult.ERROR("对不起您还未登录",-2);
        }
        //Integer userId = 124;
        Integer userId = user.getUserId();
        Map<String,Object> map = sktCartsService.appOrderPay(userId,addressId,isInvoice,invoiceClient,orderRemarks);
        Integer code = (Integer)map.get("code");
        if(code == 0){
            String msg = (String)map.get("msg");
            return AppResult.ERROR(msg);
        }
//        List<String> list = (List<String>)map.get("list");
        return AppResult.OK("提交订单成功!",map);
    }
    //切换地址重新获取运费(立即买单结算)
    @RequestMapping(value = "/Carts/newAddressBuy")
    @ResponseBody
    public AppResult newAddressBuy(@ModelAttribute("shopId") Integer shopId,
			  						 @ModelAttribute("cityId") Integer areaId2){
        Map<String,Integer> mmp = new HashMap<String,Integer>();
    	Integer allAddressPrice = sktCartsService.appnewAddressBuy(shopId, areaId2);
    	if(allAddressPrice == null){
            mmp.put("allAddressPrice",0);
        }else {
            mmp.put("allAddressPrice", allAddressPrice);
        }
    	return AppResult.OK("",mmp);
    }
    //切换地址重新获取运费（购车结算）
    @RequestMapping(value = "/Carts/newAddressPrice")
    @ResponseBody
   //Modify "userId" Into "shopId" by GaoTing on 2018-6-27 04:48:11
    public AppResult newAddressPrice(@ModelAttribute("cityId") Integer areaId2){
    /*	SktCarts sc = new SktCarts();
    	SktCarts uid = sc.selectById(userId);
    	Integer goodsId = uid.getGoodsId();*/
        //获取用户ID
        Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
        if(user == null){
            return AppResult.ERROR("对不起您还未登录",-2);
        }
        //Integer userId = 124;
        Integer userId = user.getUserId();
        Map<String, Object> map = sktCartsService.newAddressPrice(userId, areaId2);
        Integer code = (Integer)map.get("code");
        if(code == 0){
            String msg = (String)map.get("msg");
            return AppResult.ERROR(msg);
        }
        return AppResult.OK("",map);
//    	Map<String,Integer> mmp = sktCartsService.newAddressPrice(userId, areaId2);
//    	if(mmp != null && mmp.size() > 0){
//            return AppResult.OK("freight",mmp);
//        }
//    	Map<String,Integer> map = new HashMap<String,Integer>();
//        Integer put = map.put("freight", 0);
//        return AppResult.OK("freight",put);
}
    /**
     *
     * @param code 支付场景
     * @return
     */
    @RequestMapping(value = "/User/accountConfig")
    @ResponseBody
    public AppResult appAccountConfig(@ModelAttribute("code")String code){
        //获取用户登录信息
        Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
        if(user == null){
            return AppResult.ERROR("对不起您还未登录",-2);
        }
        Integer userId = user.getUserId();
        if(code.equals("Carts")){
            code = "BUY_GOODS";
        }
        Map<String,Object> map = sktCartsService.appAccountConfig(userId,code);
        Integer co = (Integer)map.get("code");
        if(co == 0){
            String msg = (String)map.get("msg");
            return AppResult.ERROR(msg);
        }
        return AppResult.OK("查询成功",map);
    }

    /**
     * 支付(现金，开元宝，开元宝货款)
     * @param orderNo
     * @param payType   支付方式 2 现金 3开元宝 6开元宝货款
     * @param payPwd
     * @param isBatch  "1"是否是购物车进 1：购物车进  0 未进入
     * @return
     */
    @RequestMapping(value = "/orders/payCashKaiyuan")
    @ResponseBody
    public AppResult appPayCashKaiyuan(@ModelAttribute("orderNo")String orderNo,
                                       @ModelAttribute("payType")Integer payType,
                                       @ModelAttribute("payPwd")String payPwd,
                                       @ModelAttribute("isBatch")Integer isBatch,
                                       @ModelAttribute("thirdNo") String thirdNo,
                                       @ModelAttribute("thirdType") Integer thirdType,
                                       @ModelAttribute("payName") String payName) {
        //获取用户登录信息
        Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
        if(user == null){
            return AppResult.ERROR("对不起您还未登录",-2);
        }
        Integer userId = user.getUserId();
        //校验登录密码
//        JSONObject jsonObject = checkPwd(payPwd, "payPwd");
        //获取校验状态
//        Integer code = Integer.parseInt(jsonObject.get("status").toString());
//        if(code == -1){
//            String msg = jsonObject.get("msg").toString();
//            return AppResult.ERROR(msg);
//        }


        //付钱加库存
    //    Map<String,Object> map = sktCartsService.appPayCashKaiyuan(userId,payType,orderNo,isBatch);
        Map<String,Object> map = sktCartsService.newAppPayCashKaiyuan(userId,payType,orderNo,isBatch,thirdNo,thirdType,payName);
        Integer code1 = Integer.parseInt(map.get("code").toString());
        if(code1 == 00){
            String msg = map.get("msg").toString();
            return  AppResult.ERROR(msg);
        }
        return AppResult.OK("支付成功",map);
    }

    /**
     *购物车选中商品
     * @return
     */
    @RequestMapping(value = "/Carts/checkCarts")
    @ResponseBody
    public AppResult appCheckCarts(){
        //获取用户登录信息
        Users user = (Users) cacheUtil.get(SessionUtils.getSessionId());
        if(user == null){
            return AppResult.ERROR("对不起您还未登录",-2);
        }
        Integer userId = user.getUserId();
        Map<String,Object> map = sktCartsService.appCheckCarts(userId);
        Integer code = (Integer) map.get("code");
        if(code == 0){
            String msg = (String)map.get("msg");
            return AppResult.ERROR(msg);
        }
        return AppResult.OK("",map);
    }

    /**
     * H5更新购物车商品数量
     */
    @RequestMapping(value = "/Carts/updateCartNum")
    @ResponseBody
    public AppResult updateCartNum(@ModelAttribute("cartId")String cartId,@ModelAttribute("cartNum")String cartNum){
        //获取用户登录信息
        Users user = (Users) cacheUtil.get(SessionUtils.getSessionId());
        if(user == null){
            return AppResult.ERROR("对不起您还未登录",-2);
        }
        Integer userId = user.getUserId();
            Map<String,Object> map = sktCartsService.updateCartNum(cartId,cartNum);
        Object code = map.get("code");
        if("00".equals(code.toString())){
            return AppResult.ERROR(map.get("msg").toString());
        }
        return AppResult.OK("成功");
    }

    /**
     * H5购物车 结算
     * @param addressId
     * @param isInvoice  是否需要发票
     * @param invoiceClient  发票抬头
     * @param orderRemarks 订单备注集合
     * @return
     */
    @RequestMapping(value = "/Orders/h5orderPay")
    @ResponseBody
    public AppResult h5appOrderPay(@ModelAttribute("addressId")Integer addressId,
                                 @ModelAttribute("isInvoice")Integer isInvoice,
                                 @ModelAttribute("invoiceClient") String invoiceClient,
                                 @ModelAttribute("orderRemarks") String orderRemarks){
        //获取用户ID
        Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
        if(user == null){
            return AppResult.ERROR("对不起您还未登录",-2);
        }
        //Integer userId = 124;
        Integer userId = user.getUserId();
        JSONArray objects = JSONArray.parseArray(orderRemarks);
        List<Map> maps = objects.toJavaList(Map.class);
        Map<String,Object> map = sktCartsService.h5appOrderPay(userId,addressId,isInvoice,invoiceClient,maps);
        Integer code = (Integer)map.get("code");
        if(code == 0){
            String msg = (String)map.get("msg");
            return AppResult.ERROR(msg);
        }
//        List<String> list = (List<String>)map.get("list");
        return AppResult.OK("提交订单成功!",map);
    }

}
